package raceReservationServer.dao;


import java.sql.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.Date;

import raceReservationServer.dao.IRaceServerDAO;

public class RaceServerDAO implements IRaceServerDAO{
	
	private Connection connection = null;  
	private int countPlaces;
	private Date date;
	static private RaceServerDAO instance = null;
	
	private RaceServerDAO()
	{
		
	}
	
	static public RaceServerDAO getInstance()
	{
		if(instance == null)
		{
			instance = new RaceServerDAO();
		}
		return instance;
	}
	
	public void connect()
	{
		try
		{
			Class.forName("org.sqlite.JDBC");
			connection = DriverManager.getConnection("jdbc:sqlite:db/rmi-db/reservations.db");   
		}
		catch (ClassNotFoundException e) {e.printStackTrace();}
		catch (SQLException e) {System.out.println("Unable to connect to reservations.db");}
	}

	public int getPlacesCount(String raceServer, String raceName)
	{
		Statement statement = null;
		try {
			statement = connection.createStatement();
		} catch (SQLException e) {
			System.out.println("Fallo statement");
			e.printStackTrace();
		}
		try
		{
			ResultSet resultSet = statement.executeQuery("Select COUNT(*) reservations from reservations where UPPER(\"race-server\") like '"+raceServer+"' and UPPER(\"race-name\") like '"+raceName+"';");
			countPlaces = resultSet.getInt("reservations");
			statement.close();
			resultSet.close();
		}
		catch (SQLException e) {e.printStackTrace();}
		return countPlaces;
	}

	public void reservePlace(String runnerName, String raceServer, String raceName)throws SQLException
	{
		Statement statement = null;
		
		statement = connection.createStatement();
		
		
		java.util.Date utilDate = new java.util.Date();
		long miliseconds = utilDate.getTime();
		java.sql.Date reservationDate = new java.sql.Date(miliseconds);

		statement.executeUpdate("INSERT INTO reservations VALUES('" + runnerName + "','" + raceServer + "','" + raceName + "','" + reservationDate + "');");
		statement.close();
	
		
	}

	public void disconnect()
	{
		try
		{
			connection.close();
		}
		catch (SQLException e) {e.printStackTrace();}
		
	}

}
